<template>
  <div>
    <van-nav-bar :title="t('home.cutOffProcessing')" left-arrow @click-left="onClickLeft" placeholder fixed />

    <scanning @keydownEnter="handleScan" :placeholder="t('cutOffProcessing.pleaseScanningNumber')" :isFocus="true"
      :isReset="true"></scanning>
    <van-cell-group style="background: none; height: calc( 100vh - 160px); overflow: auto">
      <van-form @submit="onSubmit">
        <van-field v-model="form.providerTrackingNo" disabled :label="t('抓码比对.物流商单号')"
          class="mt-2" />
        <van-field v-model="form.customerCode" type="number" disabled :label="t('cutOffProcessing.customCode')" />

        <van-cell title="物品信息" value="" />
        <van-field style="background-color: #eee;">
          <template #input>
            <van-col span="7" style="text-align: center">
              {{ t('sku') }}
            </van-col>
            <van-col span="7" style="text-align: center">
              {{ t('cutOffProcessing.count') }}
            </van-col>
            <van-col span="10" style="text-align: center">
              {{ t('cutOffProcessing.locationCode') }}
            </van-col>
          </template>
        </van-field>
        <div style="margin-bottom: 20px;">
          <van-field v-for="(item, index) in orderFormList" :key="index">
            <template #input>
              <van-col span="7" style="text-align: center">
                {{ item.goodsSkuCode }}
              </van-col>
              <van-col span="7" style="text-align: center">
                {{ item.goodsQuantity }}
              </van-col>
              <van-col span="10" style="text-align: center">
                {{ item.locationCode }}
              </van-col>
            </template>
          </van-field>
        </div>
        <scanning ref="locationCodeRef" @keydownEnter="handleScanLocationCode"
          :placeholder="t('cutOffProcessing.pleaseScanlocationCode')" style="height: 50px"></scanning>
        <scanning ref="containerCodeRef" @keydownEnter="handleScanContainerCode" :placeholder="t('抓码比对.请扫描流转箱号')"
          style="height: 50px; display: none"></scanning>
        <div style="display: flex; align-items: center;">
          <scanning ref="skuCodeRef" @keydownEnter="handleScanSkuCode" :placeholder="t('抓码比对.请扫描SKU')"
            style="height: 50px; width: 75vw"></scanning>
          <div style="background: white; width: 20vw; height: 50px; color: #b2acac">
            <div v-if="curGood ? curGood.scanNum : null" style="text-align: center; line-height: 50px;">
              {{ curGood ? curGood.scanNum : null }}
            </div>
            <div v-else style="text-align: center; line-height: 50px;">
              {{ t('抓码比对.扫描数量') }}
            </div>
          </div>
        </div>
      </van-form>
    </van-cell-group>
    <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '30%' }">
      <van-button type="success" size="small" style="width: 4rem" @click="orderUploadSubmit">{{ t('抓码比对.上传')
      }}</van-button>
      <van-field>
        <template #input>
          <van-col span="6" style="text-align: center">
            {{ t('sku') }}
          </van-col>
          <van-col span="6" style="text-align: center">
            {{ t('cutOffProcessing.count') }}
          </van-col>
          <van-col span="8" style="text-align: center">
            {{ t('cutOffProcessing.locationCode') }}
          </van-col>
          <van-col span="4" style="text-align: center">
            {{ t('抓码比对.状态') }}
          </van-col>
        </template>
      </van-field>
      <div style="height: 68%; overflow: auto">
        <van-checkbox-group v-model="selection">
          <van-field v-for="(item, index) in orderFormList" :key="index">
            <template #input>
              <van-col span="6" style="text-align: center">
                {{ item.goodsSkuCode }}
              </van-col>
              <van-col span="6" style="text-align: center">
                {{ item.goodsQuantity }}
              </van-col>
              <van-col span="8" style="text-align: center">
                {{ item.locationCode }}
              </van-col>
              <van-col span="4" :style="{
                textAlign: 'center'
              }">
                {{ item.status || "N" }}
              </van-col>
            </template>
          </van-field>
        </van-checkbox-group>
      </div>
    </van-popup>
    <div style="position: absolute; bottom: 0; display: flex; width: 100%;">
      <van-button block type="primary" @click="orderSubmit" style="height: 9vh">{{ t('抓码比对.确认') }}</van-button>
      <van-button block type="warning" @click="orderUpload" style="height: 9vh">{{ t('抓码比对.等待上传') }}（{{ len
      }}）</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Scanning from "@/views/components/Scanning/index.vue";
import { postRequest, scanSuccess, scanFail } from "@/api";
import { AppToast } from "@/utils/appToast";
const locationCodeRef = ref(null)
const containerCodeRef = ref(null)
const skuCodeRef = ref(null)
const showBottom = ref(false)
const selection = ref([])
// let index = 0
const { t } = useI18n();
const onClickLeft = () => history.back();
const form = ref();
const resetForm = () => {
  form.value = {
    orderNo: undefined,
    providerTrackingNo: undefined,
    customCode: undefined,
    deliveredBoxNum: undefined,
    undeliveredBoxNum: undefined,
    arrivalBoxNum: undefined,
  }
};

interface OrderForm {
  goodsSkuCode: string,
  goodsQuantity: number,
  locationCode: string,
  containerCode: string,
  status: string,
  scanNum: number,
};
let orderFormList: OrderForm[] = [];
let orderFormListSameLocation: OrderForm[] = [];
let len = ref(0);

let curGood = ref();
curGood.value = {
  goodsSkuCode: undefined,
  goodsQuantity: undefined,
  locationCode: undefined,
  containerCode: undefined,
  scanNum: undefined,
}

resetForm();
const handleScan = async orderNo => {
  resetForm();
  postRequest(
    '/outbound/outBoundOrder/queryOutboundOrderPageList',
    { orderNo }
  ).then(res => {
    if (!res || res.returnCode !== 10000 || !res.data) return
    if (res.data?.dataList?.length > 0) {
      scanSuccess()
      form.value = {
        ...res.data?.dataList[0]
      }
      orderFormList = res.data.dataList[0].goodsList;
      if (res.data.dataList[0].goodsList?.length > 0) {
        // curGood.value = res.data.dataList[0].goodsList[index];
        // curGood.value.scanNum = 0;
      }
      len.value = orderFormList.length
      locationCodeRef.value.setFocus()
    } else {
     // scanFail()
      postRequest(
        '/outbound/outBoundOrder/queryOutboundOrderPageList',
        { providerTrackingNo: orderNo }
      ).then(res => {
        if (!res || res.returnCode !== 10000 || !res.data) return
        if (res.data?.dataList?.length > 0) {
          scanSuccess()
          form.value = {
            ...res.data?.dataList[0]
          }
          orderFormList = res.data.dataList[0].goodsList;
          if (res.data.dataList[0].goodsList?.length > 0) {
            // curGood.value = res.data.dataList[0].goodsList[index];
            // curGood.value.scanNum = 0;
          }
          len.value = orderFormList.length
          locationCodeRef.value.setFocus()
        } else {
          scanFail()
        }
      }).catch(() => {
        scanFail()
      })
    }
  }).catch(() => {
    scanFail()
  })
}
const handleScanLocationCode = value => {
  // if (curGood.value.locationCode !== value) {
  //   scanFail()
  //   AppToast(t("cutOffProcessing.locationCodeIsFalse"), "fail")
  //   locationCodeRef.value.setValue(undefined)
  //   return
  // }
  orderFormListSameLocation = orderFormList?.filter(item => item.locationCode === value)
  if (orderFormListSameLocation.length > 0) {
    scanSuccess()
    AppToast(t("cutOffProcessing.locationCodeScanSuccess"), "success")
    // containerCodeRef.value.setFocus()
    // containerCodeRef.value.setValue(curGood.value.containerCode)
    skuCodeRef.value.setFocus()
  } else {
    scanFail()
    AppToast(t("cutOffProcessing.locationCodeIsFalse"), "fail")
    locationCodeRef.value.setValue(undefined)
  }
}
const handleScanContainerCode = value => {
  if (curGood.value.containerCode !== value) {
    scanFail()
    AppToast(t("抓码比对.流转箱号不正确"), "fail")
    containerCodeRef.value.setValue(undefined)
    return
  }
  scanSuccess()
  AppToast(t("抓码比对.流转箱号扫描成功"), "success")
  skuCodeRef.value.setFocus()
}
const handleScanSkuCode = async value => {
  curGood.value = orderFormListSameLocation.find(item => item.goodsSkuCode === value)
  // if (curGood.value.goodsSkuCode !== value) {
  //   scanFail()
  //   AppToast(t("抓码比对.SKU不正确"), "fail")
  //   skuCodeRef.value.setValue(undefined)
  //   return
  // }
  if (!curGood.value) {
    scanFail()
    AppToast(t("抓码比对.SKU不正确"), "fail")
    skuCodeRef.value.setValue(undefined)
    return
  }
  if (!curGood.value.scanNum) {
    curGood.value.scanNum = 0
  }

  if (curGood.value.scanNum === curGood.value.goodsQuantity) {
    scanFail()
    AppToast(t("抓码比对.SKU已足够"), "fail")
    skuCodeRef.value.setValue(undefined)
    return
  }
  scanSuccess()
  AppToast(t("抓码比对.SKU扫描成功"), "success")
  containerCodeRef.value.setValue(curGood.value.containerCode)
  curGood.value.scanNum++
  if (curGood.value.scanNum === curGood.value.goodsQuantity) {
    curGood.value.status = 'Y'
  } else {
    skuCodeRef.value.setValue(undefined)
    return;
  }
  const goodsList = orderFormList
  const goods = goodsList.find(d => d.status !== 'Y');
  if (goods) {
    // curGood.value = goods
    // curGood.value.scanNum = 0;
    curGood.value = {
      goodsSkuCode: undefined,
      goodsQuantity: undefined,
      locationCode: undefined,
      containerCode: undefined,
      scanNum: undefined,
    }
    locationCodeRef.value.setFocus()
    locationCodeRef.value.setValue(undefined)
    containerCodeRef.value.setValue(undefined)
    skuCodeRef.value.setValue(undefined)
    return;
  }
}

const onSubmit = () => {
  // TODO
}
const orderSubmit = () => {
  if (orderFormList?.length > 0) {
    if (curGood.value.scanNum === curGood.value.goodsQuantity) {
      curGood.value.status = "Y";
      curGood.value.scanNum = 0;
      locationCodeRef.value.setValue(undefined)
      containerCodeRef.value.setValue(undefined)
      skuCodeRef.value.setValue(undefined)
    } else {
      AppToast('拣货数量与订单sku数量不一致', 'fail');
    }
  }
}

const orderUpload = () => {
  showBottom.value = true
}

const orderUploadSubmit = () => {
  if (orderFormList.length === 0) {
    AppToast(t("抓码比对.选中订单不存在"), "fail")
    return
  }
  const order = orderFormList.find(d => d.status !== 'Y');
  if (order) {
    if (!order.status || order.status === "N") {
      AppToast(t("抓码比对.有订单状态为N_不能上传"), "fail")
      return
    }
  }

  postRequest("/intercept/interceptHandle", {
    outboundNo: form.value.orderNo
  }).then(() => {
    AppToast(t("抓码比对.上传成功"), "success")
    resetForm()

    showBottom.value = false
    orderFormList = []
    curGood.value.scanNum = 0
    len.value = orderFormList.length
    locationCodeRef.value.setValue(undefined)
    containerCodeRef.value.setValue(undefined)
    skuCodeRef.value.setValue(undefined)
  })
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-button) {
  font-size: 1rem;
}

:deep(.van-field--disabled .van-field__label) {
  color: black;
}

:deep(.van-uploader__upload) {
  width: 120px;
  height: 120px;
}
</style>
